package com.atguigu.gmall.pms.service.impl;

import com.atguigu.gmall.common.bean.PageParamVo;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.pms.client.GmallSmsClient;
import com.atguigu.gmall.pms.entity.*;
import com.atguigu.gmall.pms.mapper.SkuMapper;
import com.atguigu.gmall.pms.mapper.SpuDescMapper;
import com.atguigu.gmall.pms.mapper.SpuMapper;
import com.atguigu.gmall.pms.service.SkuAttrValueService;
import com.atguigu.gmall.pms.service.SkuImagesService;
import com.atguigu.gmall.pms.service.SpuAttrValueService;
import com.atguigu.gmall.pms.service.SpuService;
import com.atguigu.gmall.pms.vo.SkuVo;
import com.atguigu.gmall.pms.vo.SpuAttrValueVo;
import com.atguigu.gmall.pms.vo.SpuVo;
import com.atguigu.gmall.sms.vo.SkuSaleVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.lang.Collections;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service("spuService")
public class SpuServiceImpl extends ServiceImpl<SpuMapper, SpuEntity> implements SpuService {

    @Autowired
    private SpuDescMapper descMapper;

    @Autowired
    private SpuAttrValueService spuAttrValueService;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private SkuAttrValueService skuAttrValueService;

    @Autowired
    private SkuImagesService imagesService;

    @Autowired
    private GmallSmsClient smsClient;

    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<SpuEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<SpuEntity>()
        );

        return new PageResultVo(page);
    }
    //查询spu信息
    @Override

    public PageResultVo querySpuInfo(Long cid, PageParamVo pageParamVo) {

        //构建查询条件构造器
        QueryWrapper<SpuEntity> wrapper = new QueryWrapper<>();
        //判断cid
        if (cid != 0){
            wrapper.eq("category_id", cid);
        }
        //搜索关键字
        String key = pageParamVo.getKey();
        if (StringUtils.isNotBlank(key)){
            wrapper.and(t ->{
               t.like("id",key).or().like("name",key);
            });
        }
        //pageparamvo.getpage 获得Ipage对象
        return new PageResultVo(this.page(pageParamVo.getPage(), wrapper));
    }
    //进行全部参数保存
    @Override
    @GlobalTransactional
    public void bigSave(SpuVo spuVo) {
        //保存spu
        //1基本信息 设置其他参数
        Long spuId = saveSpu(spuVo);
        //spu描述信息
        saveSpuDesc(spuVo, spuId);
        //spu规格信息
        saveBaseAttrs(spuVo, spuId);
        //2 保存sku信息
        saveSkus(spuVo, spuId);

//        int i = 1 / 0;
    }

    private void saveSkus(SpuVo spuVo, Long spuId) {
        List<SkuVo> skus = spuVo.getSkus();
        if (Collections.isEmpty(skus)){
            return;
        }
        skus.forEach(skuVo -> {
            //创建sku
            SkuEntity skuEntity = new SkuEntity();
            BeanUtils.copyProperties(skuVo, skuEntity);
            skuEntity.setBrandId(spuVo.getBrandId());
            skuEntity.setCatagoryId(spuVo.getCategoryId());
            skuEntity.setSpuId(spuId);
            List<String> images = skuVo.getImages();
            if(!Collections.isEmpty(images)){
                skuEntity.setDefaultImage(skuEntity.getDefaultImage()==null ? images.get(0) : skuEntity.getDefaultImage());
            }
            //保存操作
            this.skuMapper.insert(skuEntity);
            //获取skuid
            Long skuId = skuEntity.getId();
            //保存sku图片信息
            if (!Collections.isEmpty(images)){
                this.imagesService.saveBatch(images.stream().map(image -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setUrl(image);
                    skuImagesEntity.setSort(0);
                    if (StringUtils.equals(image, skuVo.getDefaultImage())){
                        skuImagesEntity.setDefaultStatus(1);
                    }
                    return skuImagesEntity;
                }).collect(Collectors.toList()));
            }
            //保存sku的销售属性
            List<SkuAttrValueEntity> saleAttrs = skuVo.getSaleAttrs();
            if(!Collections.isEmpty(saleAttrs)){
                saleAttrs.forEach(saleAttr->{
                    saleAttr.setSkuId(skuId);
                    saleAttr.setSort(0);
                });
            }
            this.skuAttrValueService.saveBatch(saleAttrs);
            //进行远程调用
            SkuSaleVo skuSaleVo = new SkuSaleVo();
            BeanUtils.copyProperties(skuVo, skuSaleVo);
            skuSaleVo.setSkuId(skuId);
            this.smsClient.saveSkuSaleInfo(skuSaleVo);
        });
    }

    private void saveBaseAttrs(SpuVo spuVo, Long spuId) {
        List<SpuAttrValueVo> baseAttrs = spuVo.getBaseAttrs();
        if (!Collections.isEmpty(baseAttrs)){
            //使用strem流的方式  baseAttrs  --> spuAttrValueEntityList
            List<SpuAttrValueEntity> spuAttrValueEntityList = baseAttrs.stream().map(spuAttrValueVo -> {
                SpuAttrValueEntity attrValueEntity = new SpuAttrValueEntity();
                //对象赋值
                BeanUtils.copyProperties(spuAttrValueVo, attrValueEntity);
                attrValueEntity.setSpuId(spuId);
                attrValueEntity.setSort(0);
                return attrValueEntity;
            }).collect(Collectors.toList());
            this.spuAttrValueService.saveBatch(spuAttrValueEntityList);
        }
    }

    private void saveSpuDesc(SpuVo spuVo, Long spuId) {
        SpuDescEntity spuDescEntity = new SpuDescEntity();
        spuDescEntity.setSpuId(spuId);
        //转换为字符串
        spuDescEntity.setDecript(StringUtils.join(spuVo.getSpuImages(), ","));
        descMapper.insert(spuDescEntity);
    }

    private Long saveSpu(SpuVo spuVo) {
        spuVo.setPublishStatus(1);
        spuVo.setCreateTime(new Date());
        spuVo.setUpdateTime(spuVo.getCreateTime());
        this.save(spuVo);
        //spuid
        return spuVo.getId();
    }

}